package cn.globalph.housekeeper.service;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;


import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;
import androidx.core.content.FileProvider;

import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadListener;
import com.liulishuo.filedownloader.FileDownloader;

import java.io.File;

import cn.globalph.housekeeper.BuildConfig;
import cn.globalph.housekeeper.R;

/**
 * Created by homelajiang on 2017/2/15 0015.
 */

public class UpdateService extends Service {

    private static final int NOTIFICATION_ID = 1;
    private static final int NOTIFICATION_FAIL = 2;
    public static final String UPDATE_URL = "update_url";
    private NotificationCompat.Builder builder;
    private NotificationManager notificationManager;
    public static int pro;
    private boolean progressing;
    private String channel_id = "121";

    @Override
    public void onCreate() {
        super.onCreate();
        notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(channel_id,
                    "housekeeper", NotificationManager.IMPORTANCE_DEFAULT);
            channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);//设置是否应在锁定屏幕上显示此频道的通知
            channel.setDescription("品荟管家");//设置渠道描述
            notificationManager.createNotificationChannel(channel);
        }
        builder = new NotificationCompat.Builder(this, channel_id);

        builder.setSmallIcon(R.mipmap.ic_launcher);
        builder.setWhen(System.currentTimeMillis());
        builder.setPriority(NotificationCompat.PRIORITY_MAX);
        builder.setOnlyAlertOnce(true);
        builder.setContentTitle("下载更新");
        builder.setContentText("等待下载");
        builder.setProgress(0, 0, true);
        startForeground(NOTIFICATION_ID, builder.build());
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if(intent != null){
            String updateUrl = intent.getStringExtra(UPDATE_URL);
            Log.i("UpdateService","onStartCommand;"+updateUrl);
            downloadUpdateFile(updateUrl);
        }
        return START_STICKY;
    }

    private void downloadUpdateFile(String url) {
        File cacheDir = getExternalCacheDir();
        final File localFile = new File(cacheDir, "tempApkFile");
        if(localFile.exists()){
            Log.i("UpdateService","fileExist");
        }else{
            Log.i("UpdateService","fileisNotExist");
        }
        if (localFile.exists() && !localFile.delete()) {
            notificationFail();
            return;
        }
        Log.i("UpdateService","downloadUpdateFile:startDownload");
        FileDownloader.getImpl()
                .create(url)
                .setPath(localFile.getAbsolutePath())
                .setListener(new FileDownloadListener() {
                    @Override
                    protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {

                    }

                    @Override
                    protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                        pro = soFarBytes / (totalBytes / 100);
                        if (!progressing) {
                            progressing = true;
                            handler.post(progressRunnable);
                        }
                    }

                    @Override
                    protected void completed(BaseDownloadTask task) {
                        pro = 100;
                        handler.removeCallbacks(progressRunnable);
                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                Intent intent = new Intent(Intent.ACTION_VIEW);
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                                    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                    Uri contentUri = FileProvider.getUriForFile(UpdateService.this, BuildConfig.APPLICATION_ID + ".fileProvider", localFile);
                                    intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
                                } else {
                                    intent.setDataAndType(Uri.fromFile(localFile), "application/vnd.android.package-archive");
                                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                }
                                notificationSuccess();
                                startActivity(intent);
                                stopSelf();
                            }
                        }, 500);
                    }

                    @Override
                    protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {

                    }

                    @Override
                    protected void error(BaseDownloadTask task, Throwable e) {
                        handler.removeCallbacks(progressRunnable);
                        notificationFail();
                    }

                    @Override
                    protected void warn(BaseDownloadTask task) {

                    }
                })
                .start();
    }

    private void notificationSuccess() {
        stopForeground(true);
    }

    private void notificationFail() {
        stopForeground(false);
        builder.setContentTitle("更新下载失败")
                .setContentText("")
                .setProgress(0, 0, false);
        notificationManager.notify(NOTIFICATION_ID, builder.build());
        stopSelf();
    }

    private Handler handler = new Handler();
    private Runnable progressRunnable = new Runnable() {
        @Override
        public void run() {
            builder.setProgress(100, pro, false)
                    .setContentText("已下载 " + pro + "%");
            notificationManager.notify(NOTIFICATION_ID, builder.build());
            handler.postDelayed(progressRunnable, 1000);
        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        handler.removeCallbacks(progressRunnable);
    }
}
